﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using DataAccess.DataObject;
using DataAccess.BusinessObject;
using System.Globalization;
using System.Threading;
using System.Net.Configuration;

namespace EnmineKaitlin.admin
{
    public partial class product_new : Common.PageBase
    {
        int ProductID = 0;
        const string module = "manage-post";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (CheckPermission(module))
            {                
                if (!IsPostBack)
                {
                    try
                    {
                        if (Request["p"] != null)
                        {
                            ProductID = int.Parse(Request["p"].ToString());
                        }
                        if (ProductID > 0)
                        {                            
                            ProductID = int.Parse(Request["p"].ToString());
                            lblFunction.Text = "Cập nhật sản phẩm";
                            pnlAddProduct.Visible = false;
                            pnlEditProduct.Visible = true;
                            BindDetailProduct(ProductID);                            
                        }
                        else
                        {
                            lblFunction.Text = "Thêm sản phẩm";
                            txtCreateDate.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                            btnAdd.Text = "Thêm sản phẩm";
                            btnAdd.DataBind();
                            bindckeditor(ckeDescription);
                            BindCategory(cblCategory, 0, -1, "vn");
                            BindCoupon(cblCoupon);
                        }
                    }
                    catch (Exception ex)
                    {
                        Response.Redirect("~/admin/Default.aspx");
                    }
                }
            }
            else
            {
                Response.Redirect("~/admin/permission-fail.aspx");
            }
        }
        protected void ddlLanguage_SelectedIndexChange(object sender, EventArgs e)
        {
            if (cblCategory != null)
            {
                cblCategory.Items.Clear();
                BindCategory(cblCategory, 0, -1, ddlLanguage.SelectedValue);
            }
        }
        protected void ddlLanguageDetail_SelectedIndexChange(object sender, EventArgs e)
        {
            try
            {
                if (Request["p"] != null)
                {
                    ProductID = int.Parse(Request["p"].ToString());
                }
                if (ProductID > 0)
                {
                    CheckBoxList cblCatDetail = (CheckBoxList)rptDetailProduct.Items[0].FindControl("cblCategory");
                    cblCatDetail.Items.Clear();
                    BindCategory(cblCatDetail, 0, -1, ((DropDownList)rptDetailProduct.Items[0].FindControl("ddlLanguageDetail")).SelectedValue);
                    SelectCategory(ProductID, cblCatDetail);
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("~/admin/Default.aspx");
            }

        }
        /// <summary>
        /// Thêm mới/lưu bài viết
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, CommandEventArgs e)
        {            
            if (cblCategory.SelectedValue == "")
            {
                lblNotice.Text = "Lỗi: Bạn phải chọn ít nhật một chuyên mục cho bài viết !";
                return;
            }
            _OProduct.Name = txtName.Text;
            try{
                _OProduct.Price = int.Parse(txtPrice.Text);
            }catch(Exception ex)
            {
                _OProduct.Price = 0;
            }
            _OProduct.Description = ckeDescription.Text;
            _OProduct.CreateDate = DateTime.Parse(txtCreateDate.Text, culture, DateTimeStyles.NoCurrentDateDefault);
            _OProduct.ModifiedDate = DateTime.Now;
            _OProduct.FeaturedImage = hdfFeaturedImage.Value;
            _OProduct.SeoUrl = "";
            _OProduct.CreateUser = int.Parse(Session["user_id"].ToString());
            _OProduct.LangID = ddlLanguage.SelectedValue;
            _OProduct.Status = e.CommandArgument.ToString();
            _OProduct.Images = ckeImages.Text;
           
            List<int> lstCatID = new List<int>();
            foreach (ListItem li in cblCategory.Items)
            {
                if (li.Selected)
                {
                    lstCatID.Add(int.Parse(li.Value));
                }
            }
            List<int> lstCoupon = new List<int>();
            foreach (ListItem li in cblCoupon.Items)
            {
                if (li.Selected)
                {
                    lstCoupon.Add(int.Parse(li.Value));
                }
            }
            if (_BProduct.Add(_OProduct, lstCatID, lstCoupon))
            {
                Response.Redirect("~/admin/product-new.aspx?p=" + _BProduct.GetIDLastRecord().ToString());
            }            
        }

        /// <summary>
        /// Bind chi tiết bài viết vào form cập nhật
        /// </summary>
        /// <param name="ProductID"></param>

        protected void BindDetailProduct(int ProductID)
        {
            IList<OProduct> lstProductDetail = _BProduct.Get(ProductID);
            rptDetailProduct.DataSource = lstProductDetail;
            rptDetailProduct.DataBind();
            ddlLanguage.SelectedValue = lstProductDetail[0].LangID;
            ddlLanguage.DataBind();
            CheckBoxList cblCatDetail = (CheckBoxList)rptDetailProduct.Items[0].FindControl("cblCategory");
            BindCategory(cblCatDetail, 0, -1, lstProductDetail[0].LangID);
            SelectCategory(ProductID, (CheckBoxList)rptDetailProduct.Items[0].FindControl("cblCategory"));
            CheckBoxList cblCouponDetail = (CheckBoxList)rptDetailProduct.Items[0].FindControl("cblCoupon");
            BindCoupon(cblCouponDetail);
            SelectCoupon(ProductID, (CheckBoxList)rptDetailProduct.Items[0].FindControl("cblCoupon"));
        }

        /// <summary>
        /// Cập nhật bài viết
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void rptDetailProduct_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Update")
                {
                    if (Request["p"] != null)
                    {
                        ProductID = int.Parse(Request["p"].ToString());
                    }
                    if (ProductID > 0)
                    {
                        
                            _OProduct.ProductID = ProductID;
                            _OProduct.Name = ((TextBox)e.Item.FindControl("txtName")).Text;
                            try
                            {
                                _OProduct.Price = int.Parse(((TextBox)e.Item.FindControl("txtPrice")).Text);
                            }
                            catch (Exception ex)
                            {
                                _OProduct.Price = 0;
                            }
                            _OProduct.Description = ((CKEditor.NET.CKEditorControl)e.Item.FindControl("ckeDescription")).Text;
                            _OProduct.CreateDate = DateTime.Parse(((TextBox)e.Item.FindControl("txtCreateDate")).Text, culture, DateTimeStyles.NoCurrentDateDefault);
                            _OProduct.ModifiedDate = DateTime.Now;
                            _OProduct.FeaturedImage = ((HiddenField)e.Item.FindControl("hdfFeaturedImage")).Value;
                            _OProduct.SeoUrl = "";
                            _OProduct.LangID = ((DropDownList)e.Item.FindControl("ddlLanguageDetail")).SelectedValue;
                            _OProduct.Status = e.CommandArgument.ToString();
                            _OProduct.Images = ((CKEditor.NET.CKEditorControl)e.Item.FindControl("ckeImages")).Text;
                            List<int> lstCatID = new List<int>();
                            if ((CheckBoxList)e.Item.FindControl("cblCategory") != null)
                            {
                                foreach (ListItem li in ((CheckBoxList)e.Item.FindControl("cblCategory")).Items)
                                {
                                    if (li.Selected)
                                    {
                                        lstCatID.Add(int.Parse(li.Value));
                                    }
                                }
                            }
                            List<int> lstCouponID = new List<int>();
                            if ((CheckBoxList)e.Item.FindControl("cblCoupon") != null)
                            {
                                foreach (ListItem li in ((CheckBoxList)e.Item.FindControl("cblCoupon")).Items)
                                {
                                    if (li.Selected)
                                    {
                                        lstCouponID.Add(int.Parse(li.Value));
                                    }
                                }
                            }
                            if (_BProduct.Update(_OProduct, lstCatID, lstCouponID))
                            {
                                BindDetailProduct(_OProduct.ProductID);
                            }
                     }                    
                }
                else if (e.CommandName == "SendMail")
                {
                    if (((CheckBox)e.Item.FindControl("cbxSend")).Checked)
                    {

                        string subject = "[subcrible-EnmineKaitlin]-" + ((TextBox)e.Item.FindControl("txtTitle")).Text;
                        string content = "<h3>" + ((TextBox)e.Item.FindControl("txtTitle")).Text + "</h3>";
                        content += ((CKEditor.NET.CKEditorControl)e.Item.FindControl("ckeContent")).Text;
                        //Send email
                        SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                        IList<OEmail> lstEmail = _BEmail.Get(1, 100);
                        List<string> lstSendTo = new List<string>();
                        foreach (OEmail objEmail in lstEmail)
                        {
                            lstSendTo.Add(objEmail.Email);
                        }
                        if (Send_Email(cfg.Network.UserName, lstSendTo, subject, content))
                        {
                            RegisterClientScriptBlock("NOTE", "<script>alert('Đã gửi nội dung bài viết tới email đăng ký');</script>");
                        }
                        else
                        {
                            RegisterClientScriptBlock("NOTE", "<script>alert('Xảy ra lỗi trong quá trình gửi mail vui lòng thử lại !');</script>");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("~/admin/Default.aspx");
            }
        }
        /// <summary>
        /// Bind trạng thái khi lưu bài viết
        /// </summary>
        /// <returns></returns>
        protected string BindCommandArgument()
        {
            return "publish";
        }
        /// <summary>
        /// Bind danh sách chuyên mục vào checkboxlist
        /// </summary>
        protected void BindCategory(CheckBoxList cblCategory, int CatParent, int level, string LangID)
        {
            ListItem li;
            String html = "";
            IList<OCategory> lstCategory = _BCategory.Get(0, CatParent, LangID,"catproduct");
            if (lstCategory.Count > 0)
            {
                level += 1;
            }
            for (int i = 0; i < level * 3; i++)
            {
                html += "-";
            }
            foreach (OCategory objCat in lstCategory)
            {
                if (objCat.CatID != HoiDap_CatID)
                {
                    li = new ListItem(html + objCat.CatName, objCat.CatID.ToString());
                    cblCategory.Items.Add(li);
                    BindCategory(cblCategory, objCat.CatID, level, LangID);
                }
            }
            cblCategory.DataBind();
        }
        protected void BindCoupon(CheckBoxList cblCoupon)
        {
            cblCoupon.DataSource = _BCoupon.Get("", "publish", "DESC", "StartDate", 1, 100);
            cblCoupon.DataTextField = "Name";
            cblCoupon.DataValueField = "CouponID";
            cblCoupon.DataBind();
        }
        protected void SelectCategory(int ProductID, CheckBoxList cblCat)
        {
            IList<OCategory_Product> lstCategory_Product = _BCategory_Product.Get(ProductID);
            foreach (OCategory_Product objCatProduct in lstCategory_Product)
            {
                foreach (ListItem li in cblCat.Items)
                {
                    if (li.Value == objCatProduct.IDCat.ToString())
                    {
                        li.Selected = true;
                    }
                }
            }
        }
        protected void SelectCoupon(int ProductID, CheckBoxList cblCoupon)
        {
            IList<OCoupon_Product> lstCoupon_Product = _BCoupon_Product.Get(ProductID);
            foreach (OCoupon_Product objCouponProduct in lstCoupon_Product)
            {
                foreach (ListItem li in cblCoupon.Items)
                {
                    if (li.Value == objCouponProduct.IDCoupon.ToString())
                    {
                        li.Selected = true;
                    }
                }
            }
        }
    }
}